package com.wing.cms.dao;

import java.util.List;
import java.util.Map;

import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.stereotype.Repository;

import com.wing.cms.domain.Portlet;
import com.wing.cms.domain.Template;
import com.wing.common.CommonSpringJDBC;
import com.wing.common.Constants;
import com.wing.common.util.PageBean;
import com.wing.sys.domain.Auth;

@Repository
public class TemplateDao extends CommonSpringJDBC<Template, String> {

	public PageBean findPageList(int currentPage, int pageSize, String siteId) {
		String where = " 1=1 ";
		String sql1 = " SELECT * FROM cms_template where " + where
				+ " ORDER BY id ASC " + " LIMIT " + (currentPage - 1)
				* pageSize + "," + pageSize;
		String sql2 = "select count(id) from  cms_template  where" + where;
		if (!Constants.WORK_SITE.equals(siteId)) {
			where = " t.ispub='" + Template.ISPUB_TRUE + "' or (a.type='"
					+ Auth.TYPE_TEMPLATE + "' and a.owner_id='" + siteId
					+ "' and a.res_id=t.id) ";
			sql1 = " SELECT distinct t.* FROM cms_template t,sys_auth a where "
					+ where + " ORDER BY t.id ASC " + " LIMIT "
					+ (currentPage - 1) * pageSize + "," + pageSize;
			sql2 = "select count(t.id) FROM cms_template t,sys_auth a  where"
					+ where;
		}
		String[] sqlArray = { sql1, sql2 };
		return super.findPageList(sqlArray, currentPage, pageSize);
	}

	public List<Map<String, Object>> findTemplateByUserId(String type,String userId) {
		String sql = "select * from  cms_template t where t.type = '" + type
				+ "' and (ispub = '1' or  t.id in ( select res_id from sys_auth o" +
						" where o.type = 'template' and o.owner_id = '"+userId+"'))";
		return super.getSimpleJdbcTemplate().queryForList(sql);
	}
	

	
	public Template findById(String id){
		String sql ="SELECT * FROM cms_template where id = ? ";
		List list = super.getSimpleJdbcTemplate().queryForList(sql,id);
		if(list.size()==0){
			return null;
		}
		return super.getSimpleJdbcTemplate().queryForObject(sql, ParameterizedBeanPropertyRowMapper
						.newInstance(Template.class), id);
	}
}
